#coding:utf-8
from PyQt4 import QtCore
from twisted.words.xish import domish



class IqQuery(QtCore.QObject,domish.Element):
        timeout = QtCore.pyqtSignal()
        response = QtCore.pyqtSignal("PyQt_PyObject")
        timeleft = 0              
        def __init__(self,stream,typeIq = "set",parent = None):
                QtCore.QObject.__init__(self,parent)
                domish.Element.__init__(self,(None,"iq"))
                self["type"]=typeIq
                self._timer = QtCore.QTimer()
                self._timer.setSingleShot(True)
                self._stream = stream
                self.addUniqueId()
        def send(self,to=None):
                if self.timeleft:
                        self._timer.start(self.timeleft)
                        self._timer.timeout.connect(self.cancel)
                        self._timer.timeout.connect(self.timeout)
                if not to is None:
                        self["to"] = to
                self._stream.iqWaiting[self["id"]] = self
                self._stream.send(self)
        @QtCore.pyqtSlot()
        def cancel(self):
                del self._stream.iqWaiting[self["id"]]
                if self._timer.isActive():
                        self._timer.stop()
                self.deleteLater()
        def __call__(self,xml):
                self.response.emit(xml)
                self.cancel()
                
